import {computed, defineComponent, inject, PropType, provide, VNodeTypes} from "vue";

export const contextKey = '__MDX_PROVIDER_KEY__';

export const MDXProvider = defineComponent({
  name: 'MDXProvider',
  props:{
    components: {
      type: Object as PropType<Record<string, VNodeTypes>>,
      required: true
    }
  },
  setup(props, {slots}) {
    const componentsRef = computed(() => props.components);
    provide(contextKey, componentsRef); //todo provide原理 这里props.components变了 会触发computed计算属性本身这个属性上搜集到的effect, 即componentsRef.value使用时的环境, 即是在provide里（provide也是一个effect?）

    return () => slots.default && slots.default();
  }
})

const defaultComponentsRef = computed(() => ({}));
export const useMDXComponents = (getPropsComponents: () => Record<string, VNodeTypes>) => {
  const providedComponentsRef = inject(contextKey, defaultComponentsRef); //todo 原理

  const mergedComponentsRef = computed(() => ({
    ...providedComponentsRef.value,
    ...getPropsComponents()
  }));

  return mergedComponentsRef;
};
